package com.tan.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tan.domain.Blog;
import com.tan.domain.request.BlogParam;
import com.tan.domain.response.Result;
import com.tan.domain.response.StatusCode;
import com.tan.mapper.BlogMapper;
import com.tan.service.BlogService;
import com.tan.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @description:
 * @author: longshifu
 * @time: 2022/7/14 19:09
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class BlogController {

    final String IMAGES_PRE_URL = "http://longshifu.top:9001/test/";

    @Autowired
    BlogService blogService;
    @Autowired
    BlogMapper blogMapper;
    @Autowired
    TagService tagService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostMapping("/getBlogList")
    public Result getBlogList(@RequestBody Map<String, Object> param) {
        int pageNum = (int) param.get("pagenum");
        int pageSize = (int) param.get("pagesize");
        String title = (String) param.get("title");
        Integer typeId = (Integer) param.get("typeId");
        JSONObject result = blogService.getPageByTitleOrTypeId(title, typeId, pageNum, pageSize);
        return new Result(true, StatusCode.OK, "查询博客列表成功", result);
    }

    /**
     * 修改博客分类
     *
     * @param
     * @return
     */
    @GetMapping("/editType")
    public Result editBlogType(@RequestParam("blogId") Integer blogId, @RequestParam("typeId") Integer typeId) {
        log.info("请求参数：blogId：{}， typeId: {}", blogId, typeId);
        int count = blogMapper.updateBlog(blogId, typeId, null);
        return new Result(true, StatusCode.OK, "修改博客分类成功");
    }

    /**
     * 新增博客标签
     *
     * @param blogId
     * @param tagId
     * @return
     */
    @GetMapping("/editBlogTag")
    public Result editBlogTag(@RequestParam("blogId") Integer blogId, @RequestParam("tagId") Integer tagId) {
        log.info("请求参数：blogId：{}， tagId: {}", blogId, tagId);
        int count = blogMapper.updateBlog(blogId, null, tagId);
        return new Result(true, StatusCode.OK, "新增博客标签成功");
    }

    /**
     * 通过id删除博客标签
     *
     * @param id
     * @return
     */
    @GetMapping("/deleteBlogTag/{id}")
    public Result deleteBlogTag(@PathVariable Long id) {
        log.info("请求参数 id: {}", id);
        tagService.removeById(id);
        return new Result(true, StatusCode.OK, "删除博客标签成功");
    }

    @PostMapping("/addOrEditBlog")
    public Result addOrEditBlog(@RequestBody BlogParam blogParam) {
//        BlogParam blogParam=param.get("blog");
        String pictureUrl = blogParam.getFirstPicture();
        String lastUrl = pictureUrl.substring(pictureUrl.lastIndexOf("/"));
        if (blogParam.getId() != null) {
            UpdateWrapper<Blog> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", blogParam.getId());
            blogParam.setFirstPicture(IMAGES_PRE_URL + lastUrl);
            blogMapper.update(blogParam, updateWrapper);
            // 发送消息
            blogMessage(blogParam.getTitle(), "修改");
            return new Result(true, StatusCode.OK, "修改博客成功", blogParam);
        } else {
            Blog blog = new Blog();
            BeanUtils.copyProperties(blogParam, blog);
            blog.setUserId(blogParam.getUser().getId());
            blog.setTypeId(blogParam.getType().getId());
            blog.setFirstPicture(IMAGES_PRE_URL + lastUrl);
            blogService.save(blog);
            // 发送消息
            blogMessage(blog.getTitle(), "新增");
            return new Result(true, StatusCode.OK, "新增博客成功");
        }
    }


    @GetMapping("/editBlogFirstPicture")
    public Result editBlogFirstPicture(@RequestParam("blogId") Integer blogId, @RequestParam("firstPicture") String firstPicture) {
        UpdateWrapper<Blog> updateWrapper = new UpdateWrapper<>();
        String lastUrl = firstPicture.substring(firstPicture.lastIndexOf("/"));
        Blog blog = new Blog();
        updateWrapper.eq("id", blogId);
        updateWrapper.set("first_picture", IMAGES_PRE_URL + lastUrl);
        blogService.update(blog, updateWrapper);
        return new Result(true, StatusCode.OK, "修改首图成功");
    }

    @GetMapping("/editDescription")
    public Result editDescription(@RequestParam("blogId") Integer blogId, @RequestParam("description") String description) {
        UpdateWrapper<Blog> updateWrapper = new UpdateWrapper<>();
        Blog blog = new Blog();
        updateWrapper.eq("id", blogId);
        updateWrapper.set("description", description);
        blogService.update(blog, updateWrapper);
        return new Result(true, StatusCode.OK, "修改描述成功");
    }

    @GetMapping("/blogs/{id}/delete")
    public Result deleteBlog(@PathVariable Long id) {
        blogMapper.deleteById(id);
        return new Result();
    }


    public void blogMessage(String blogTitle, String operate) {
        String messageId = String.valueOf(UUID.randomUUID());
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("blogTitle", blogTitle);
        map.put("operate", operate);
        map.put("createTime", LocalDateTime.now());
        rabbitTemplate.convertAndSend("blog.exchange", "blogAddOrUpdate", map);
    }


}
